package com.otom.bcel;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FieldHelper {
	
	public static boolean isInterfaceOrAbstractClass(Class<?> fieldType) {
		return fieldType.isInterface() || (Modifier.isAbstract(fieldType.getModifiers()) && !fieldType.isPrimitive());
	}
	
	public static Field[] getFields(Class<?> clazz) {
		List<Field> fields = new ArrayList<Field>();
		fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
		
		while (clazz.getSuperclass() != Object.class) {
			clazz = clazz.getSuperclass();
			fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
		}
		
		return fields.toArray(new Field[0]);
	}
	
	public static Method[] getMethods(Class<?> clazz) {
		List<Method> methods = new ArrayList<Method>();
		methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));
		
		while (clazz.getSuperclass() != Object.class) {
			clazz = clazz.getSuperclass();
			methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));
		}
		
		return methods.toArray(new Method[0]);
	}
	
	public static Field getField(Class<?> clazz, String fieldName) throws NoSuchFieldException{
		Field[] fields = getFields(clazz);
		
		for (Field field : fields) {
			if (field.getName().equals(fieldName)) {
				return field;
			}
		}
		
		throw new NoSuchFieldException(fieldName);
	}
}
